<template>
    <section class="decoration-edit1">
        <section class="ll">

        </section>
        <section class="cc" ref="cc">
            <!-- header 不可拖拽 -->
            <div class="top-nav1" @click="selectType(0)">
                <img src="./../assets/images/topNavBlack.png">
                <span class="tit">{{ info.title }}</span>
            </div>
            <div
                    class="viewContent1"
                    @drop="drog"
                    @dragover="dragOver"
                    :style="{ backgroundColor: info.backgroundColor }"
            >
                <Draggable
                        v-model="view"
                        draggable=".item"
                >
                    <div ref="viewContent1">

                    </div>
                </Draggable>
            </div>

            <el-upload
                    ref="upload"
                    :http-request="upload"
                    :show-file-list="false"
                    multiple
                    action
                    style="display:none"
            >
            </el-upload>

        </section>
        <section class="r">

        </section>

        <div class="submit-btn">
            <el-button @click="saveAsImg">保存成图片</el-button>
            <!--            <el-button @click="restorePageData">恢复页面</el-button>-->
        </div>

    </section>
</template>

<script>
    import Draggable from 'vuedraggable'
    import html2canvas from 'html2canvas';
    export default {
        components: {
            Draggable,
        },
        data() {
            return {
                current_image_index : 1,
                url: '',
                view: [
                    {
                        type: 'info',
                        title: '页面标题'
                    }
                ],
                title: '页面标题',
                type: '',
                index: null,        // 当前组件的索引
                isPush: false,      // 是否已添加组件

                props: {},          // 传值
                isRight: false,

                className: {
                    1: 'one',
                    2: 'two',
                    3: 'three'
                },
                savedElements: []
            }
        },
        computed: {
            info() {
                return this.view[0]
            }
        },
        beforeDestroy() {
            // 在组件销毁时移除事件监听
            this.$el.removeEventListener("click", this.handleImageBoxClick);
        },
        mounted: function () {
            this.$nextTick(function () {
                // 仅在整个视图都被渲染之后才会运行的代码
                this.restorePageData();
                this.$el.addEventListener("click", this.handleImageBoxClick);
            })
        },
        methods: {
            //把当前页面<section class="cc">区域的class为viewContent1下的页面元素保存成图片并且在浏览器自动下载
            saveAsImg() {

                //todo 把class="input"下的所有input替换成span  input输入的文字保留放在span中

                let viewContent = this.$refs.cc; // 获取页面中 <section class="viewContent1"> 区域

                //
                // // 替换 .input 下的 <input> 为 <span>
                const inputs = viewContent.querySelectorAll('.el-input input');
                inputs.forEach(input => {
                    const span = document.createElement('span');
                    span.textContent = input.value; // 获取输入框的内容
                    span.style.cssText = window.getComputedStyle(input).cssText; // 保留样式
                    input.parentNode.replaceChild(span, input); // 替换 input 为 span
                });

                viewContent = this.$refs.cc; // 获取页面中 <section class="viewContent1"> 区域

                html2canvas(viewContent, {
                    backgroundColor: this.info.backgroundColor, // 可以设置背景色，避免透明区域
                    scale: 2, // 设定图像分辨率
                }).then(canvas => {
                    // 创建一个 <a> 标签，用于触发下载
                    const link = document.createElement('a');
                    link.href = canvas.toDataURL('image/png'); // 获取图片的 base64 数据 URL
                    link.download = 'page-image.png'; // 设置下载的文件名

                    // 触发下载
                    link.click();
                });
            },
            upload(params) {

                const file = params.file,
                    fileType = file.type;

                const form = new FormData();
                form.append("file", file);
                form.append("clientType", "multipart/form-data");

                const data = {
                    name: file.name,
                    url: URL.createObjectURL(file),
                    form
                }


                const itemElement = document.querySelector(`.item[data-index="${this.current_image_index}"]`);

                // 获取该 item 下的 image-box
                let imageBox = itemElement.querySelector('.image-box');

                if (!imageBox) {
                    imageBox = itemElement.querySelector('.banner');
                }
                // 清空 image-box 中的所有内容
                imageBox.innerHTML = '';


                // 创建 <a> 元素
                const aTag = document.createElement('a');

                // 创建 <img> 元素
                const imgTag = document.createElement('img');
                imgTag.src = data.url;
                imgTag.alt = 'Image';
                imgTag.style.width = '100%';
                imgTag.style.maxWidth = '100%';
                imgTag.style.height = '100%';

                // 将 <img> 添加到 <a> 中
                aTag.appendChild(imgTag);

                // 将 <a> 插入到 .image-box 中
                imageBox.appendChild(aTag);

            },
            handleImageBoxClick(event) {
                // 检查是否点击的是 .image-null 或其子元素
                const imageNull = event.target.closest(".image-null");
                if (imageNull) {
                    // 获取父级元素 .item 的 data-index 属性 获取data-index为1的div元素 清空.item的子元素.image-box下的所有内容 把
                    const item = imageNull.closest(".item");
                    if (item && item.dataset.index) {
                        console.log("点击的 data-index:", item.dataset.index);
                        this.current_image_index = item.dataset.index;
                        this.$refs['upload'].$children[0].$refs.input.click()
                    }
                }
            },
            // 保存页面元素以及样式
            buildElementTree(element) {
                return {
                    tag: element.tagName.toLowerCase(), // 元素类型
                    text: element.innerText, // 元素内容
                    styles: element.styles,
                    attributes: Array.from(element.attributes).reduce((acc, attr) => {
                        acc[attr.name] = attr.value;
                        return acc;
                    }, {}),
                    children: Array.from(element.childNodes).map(child => this.buildElementTree(child)), // 递归获取子元素
                    parent: element.parentNode ? element.parentNode.tagName.toLowerCase() : null // 保存父元素的标签名
                };
            },

            updateElement(node, result) {
                if (!node || !node.childNodes) return;

                // 更新当前节点的 name 属性
                //node.name = node.id.toString();
                // 递归更新子节点的 name 属性
                const className = node.className;
                const filterElement = result.filter(item => item.attributes.class === className)[0];
                node.styles = filterElement.styles;
                node.childNodes.forEach(child => this.updateElement(child, result));
            },

            restorePageData() {
                const viewContent1 = this.$refs.viewContent1;
                const savedElements = JSON.parse(localStorage.getItem("savedElements"));
                console.log(savedElements)
                if (savedElements && savedElements.length > 0) {
                    savedElements.forEach(elementData => {
                        this.buildDOMTree(viewContent1, elementData);
                    });
                }
            },
            buildDOMTree(parent, elementData) {
                const el = this.createElement(elementData);
                parent.appendChild(el);

                if (elementData.children && elementData.children.length > 0) {
                    elementData.children.forEach(childData => {
                        this.buildDOMTree(el, childData);
                    });
                }
            },
            createElement(elementData) {
                const el = document.createElement(elementData.tag);
                el.innerText = elementData.text;

                // 设置样式
                Object.keys(elementData.styles).forEach(styleKey => {
                    el.style[styleKey] = elementData.styles[styleKey];
                });

                // 设置属性
                Object.keys(elementData.attributes).forEach(attrKey => {
                    el.setAttribute(attrKey, elementData.attributes[attrKey]);
                });

                return el;
            },

            // 切换视图组件
            selectType(index) {
                this.isRight = false
                this.props = this.view[index]
                this.$nextTick(() => this.isRight = true)
            },
            deleteItem(e, index) {
                e.preventDefault()
                e.stopPropagation()
                this.view.splice(index, 1)
                this.isRight = false
                this.props = {}
            },
            // 拖拽类型
            dragStart(e) {
                console.log("dragStart")
                console.log(e.target)
                this.type = e.target.dataset.type
            },
            // 结束拖拽
            dragEnd(e) {
                console.log("dragEnd")
                this.$delete(this.view[this.index], 'status')
                this.isPush = false
                this.type = null
            },
            // 已放置到指定位置
            drog(e) {
                if (!this.type) { // 内容拖拽
                    return
                }
                e.preventDefault()
                e.stopPropagation()
                this.dragEnd()
            },
            // 移动中
            dragOver(e) {
                if (!this.type) { // 内容拖拽
                    return
                }
                e.preventDefault()
                e.stopPropagation()

                let className = e.target.className
                let name = className !== 'viewContent1' ? 'item' : 'viewContent1'

                const defaultData = {
                    type: this.type,    // 组件类型
                    status: 2,          // 默认状态
                    data: [],           // 数据
                    options: {},         // 选项操作
                    class: {
                        backgroundColor : this.typeList[this.type] ? this.typeList[this.type].backgroundColor : "#fff"
                    }
                }

                if (name == 'viewContent1') {
                    if (!this.isPush) {
                        console.log("1")
                        this.index = this.view.length
                        this.isPush = true
                        this.view.push(defaultData)
                    }
                } else if (name == 'item') {

                    let target = e.target
                    let [ y, h, curIndex ] = [ e.offsetY, target.offsetHeight, target.dataset.index ]
                    let direction = y < (h / 2)

                    if (!this.isPush) {
                        // Push to Top or Bottom
                        if (direction) {
                            if (curIndex == 0) {
                                console.log("2")
                                this.view.unshift(defaultData)
                            } else {
                                console.log("3")
                                this.view.splice(curIndex, 0, defaultData)
                            }
                        } else {
                            console.log("4")
                            curIndex = +curIndex + 1
                            this.view.splice(curIndex, 0, defaultData)
                        }
                    } else {
                        // Moving
                        if (direction) {
                            var i = curIndex == 0 ? 0 : curIndex - 1
                            var result = this.view[i]['status'] == 2
                        } else {
                            var i = +curIndex + 1
                            var result = this.view.length > i && this.view[i]['status'] == 2
                        }

                        if (result) return

                        const temp = this.view.splice(this.index, 1)
                        this.view.splice(curIndex, 0, temp[0])
                    }
                    this.index = curIndex
                    this.isPush = true
                }
            }
        }
    }
</script>
<style lang="scss" scoped>
    .white{
        padding-top: 0 !important;
    }
    .decoration-edit1{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 0;
        background: #f7f8f9;
        height: calc(100vh - 50px);
        position: relative;
        .ll, .r {
            width: 340px;
            height: 100%;
            padding: 15px 0;
            background: #fff;
        }
        .ll{
            ul{
                margin: 0;
                padding: 0;
                li{
                    width: 80px;
                    height: 80px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    flex-direction: column;
                    cursor: default;
                    list-style: none;
                    font-size: 14px;
                    color: #666;
                    float: left;
                    margin: 0 10px;
                    border-radius: 6px;
                    transition: all .3s;
                    cursor: pointer;
                    /*&:hover{*/
                    /*    background: #efefef;*/
                    /*}*/
                    span{
                        display: block;
                        font-size: 40px;
                        margin-bottom: 8px;
                        color: #999;
                    }
                    p{
                        display: block;
                        margin: 0;
                        font-size: 12px;
                    }
                }
            }
        }
        .cc{
            width: auto;
            max-width: 400px;
            position: relative;
            .top-nav1{
                position: absolute;
                top: 0;
                background: #fff;
                z-index: 999;
                transition: all .3s;
                & * {
                    pointer-events: none;
                }
                &:hover{
                    transform: scale(0.98);
                    border-radius: 10px;
                    overflow: hidden;
                    box-shadow: 0 0 10px #afafaf;
                }
                .tit{
                    position: absolute;
                    left: 50%;
                    bottom: 10px;
                    transform: translateX(-50%);
                }
                img{
                    max-width: 100%;
                    image-rendering: -moz-crisp-edges;
                    image-rendering: -o-crisp-edges;
                    image-rendering: -webkit-optimize-contrast;
                    image-rendering: crisp-edges;
                    -ms-interpolation-mode: nearest-neighbor;
                }
            }
            .viewContent1{
                width: 400px;
                height: 700px;
                background: #f5f5f5;
                overflow-y: auto;
                overflow-x: hidden;
                padding-top: 72px;
                box-shadow: 0 2px 6px #ccc;
                &::-webkit-scrollbar{
                    width: 6px;
                }
                &::-webkit-scrollbar-thumb{
                    background: #dbdbdb;
                }
                &::-webkit-scrollbar-track{
                    background: #f6f6f6;
                }

                .item{
                    transition: all .3s;
                    background: #fff;
                    div{
                        pointer-events: none;
                    }
                    .wait{
                        background: #deedff;
                        height: 35px;
                        text-align: center;
                        line-height: 35px;
                        font-size: 12px;
                        color: #666;
                    }

                }
            }
        }
    }
    .submit-btn{
        position: absolute;
        bottom: 30px;
        left: 50%;
        transform: translateX(-50%);
    }
    .banner{
        font-size: 0;
        img{
            width: 100%;
        }
        .el-carousel__indicator--horizontal{
            padding: 12px 4px;
        }
        .el-carousel__button{
            width: 12px;
        }
        .image-null{
            background: #ffffff;
            height: 176px;
            font-size: 50px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #c1c1c1;
        }
    }
</style>
